package com.springweb.unit5.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.springweb.unit5.dao.SpittleRepository;
import com.springweb.unit5.domain.Spittle;
import com.springweb.unit7.error.SpittleNotFoundException;

@Controller
@RequestMapping(value="spittle")
public class SpittleController {

	@Autowired
	private SpittleRepository spittleRepository;
	
	/**
	 * 
	 * Description: 获取spittle列表
	 *
	 * @param model
	 * @return
	 * @Author zhangxujun
	 * @Create Date: 2017年11月15日 下午2:09:19
	 */
	@RequestMapping(value="spittles", method=RequestMethod.GET)
	public String spittles(Model model) {
		model.addAttribute("spittles", spittleRepository.findSpittles(0, 20));
		return "unit5/spittles";
	}
	
	/**
	 * 
	 * Description: 分页获取spittle列表
	 *
	 * @param model
	 * @param max
	 * @param count
	 * @return
	 * @Author zhangxujun
	 * @Create Date: 2017年11月15日 下午2:09:45
	 */
	@RequestMapping(value="spittlesByPage", method=RequestMethod.GET)
	public String spittlesByPage(Model model, @RequestParam(value="max", defaultValue="0") long max, @RequestParam(value="count", defaultValue="20") int count) {
		model.addAttribute("spittles", spittleRepository.findSpittles(0, 20));
		return "unit5/spittles";
	}
	
	/**
	 * 
	 * Description: 根据ID获取spittle对象
	 * 查询参数（Query Parameter）
	 *
	 * @param model
	 * @param id
	 * @return
	 * @Author zhangxujun
	 * @Create Date: 2017年11月15日 上午11:55:13
	 */
	@RequestMapping(value="spittle", method=RequestMethod.GET)
	public String spittle(Model model, @RequestParam("id") long id) {
		Spittle spittle = spittleRepository.findSpittle(id);
		if (null == spittle) {
			throw new SpittleNotFoundException();
		}
		model.addAttribute("spittle", spittle);
		return "unit5/spittle";
	}
	
	/**
	 * 
	 * Description: 根据ID获取spittle对象 
	 * 路径变量（Path Variable）
	 *
	 * @param model
	 * @param id
	 * @return
	 * @Author zhangxujun
	 * @Create Date: 2017年11月15日 上午11:55:24
	 */
	@RequestMapping(value="spittlePath/{id}/{result}", method=RequestMethod.GET)
	public String spittlePath(Model model, @PathVariable("id") long id,  @PathVariable("result") String result) {
		Spittle spittle = spittleRepository.findSpittle(id);
		if (null == spittle) {
			throw new SpittleNotFoundException();
		}
		model.addAttribute("spittle", spittle);
		model.addAttribute("result", result);
		return "unit5/spittle";
	}
	
}
